package com.mfw.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfw.springboot.annotation.AuthCheck;
import com.mfw.springboot.common.BaseResponse;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.DeleteRequest;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.common.Result;
import com.mfw.springboot.constant.UserConstant;
import com.mfw.springboot.exception.BusinessException;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.model.dto.userTrainingPlanRelation.UserTrainingPlanRelationAddRequest;
import com.mfw.springboot.model.dto.userTrainingPlanRelation.UserTrainingPlanRelationEditRequest;
import com.mfw.springboot.model.dto.userTrainingPlanRelation.UserTrainingPlanRelationQueryRequest;
import com.mfw.springboot.model.dto.userTrainingPlanRelation.UserTrainingPlanRelationUpdateRequest;
import com.mfw.springboot.model.entity.UserTrainingPlanRelation;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.vo.UserTrainingPlanRelationVO;
import com.mfw.springboot.service.UserTrainingPlanRelationService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户训练计划关系接口
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/userTrainingPlanRelation")
@Slf4j
public class UserTrainingPlanRelationController {

    @Resource
    private UserTrainingPlanRelationService userTrainingPlanRelationService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建用户训练计划关系
     *
     * @param userTrainingPlanRelationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserTrainingPlanRelation(@RequestBody UserTrainingPlanRelationAddRequest userTrainingPlanRelationAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userTrainingPlanRelationAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        UserTrainingPlanRelation userTrainingPlanRelation = new UserTrainingPlanRelation();
        BeanUtils.copyProperties(userTrainingPlanRelationAddRequest, userTrainingPlanRelation);
        // 数据校验
        userTrainingPlanRelationService.validUserTrainingPlanRelation(userTrainingPlanRelation, true);

        // 写入数据库
        boolean result = userTrainingPlanRelationService.save(userTrainingPlanRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newUserTrainingPlanRelationId = userTrainingPlanRelation.getId();
        return Result.success(newUserTrainingPlanRelationId);
    }

    /**
     * 删除用户训练计划关系
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserTrainingPlanRelation(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserTrainingPlanRelation oldUserTrainingPlanRelation = userTrainingPlanRelationService.getById(id);
        ThrowUtils.throwIf(oldUserTrainingPlanRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserTrainingPlanRelation.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userTrainingPlanRelationService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新用户训练计划关系（仅管理员可用）
     *
     * @param userTrainingPlanRelationUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUserTrainingPlanRelation(@RequestBody UserTrainingPlanRelationUpdateRequest userTrainingPlanRelationUpdateRequest) {
        if (userTrainingPlanRelationUpdateRequest == null || userTrainingPlanRelationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        UserTrainingPlanRelation userTrainingPlanRelation = new UserTrainingPlanRelation();
        BeanUtils.copyProperties(userTrainingPlanRelationUpdateRequest, userTrainingPlanRelation);
        // 数据校验
        userTrainingPlanRelationService.validUserTrainingPlanRelation(userTrainingPlanRelation, false);
        // 判断是否存在
        long id = userTrainingPlanRelationUpdateRequest.getId();
        UserTrainingPlanRelation oldUserTrainingPlanRelation = userTrainingPlanRelationService.getById(id);
        ThrowUtils.throwIf(oldUserTrainingPlanRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = userTrainingPlanRelationService.updateById(userTrainingPlanRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取用户训练计划关系（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserTrainingPlanRelationVO> getUserTrainingPlanRelationVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        UserTrainingPlanRelation userTrainingPlanRelation = userTrainingPlanRelationService.getById(id);
        ThrowUtils.throwIf(userTrainingPlanRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(userTrainingPlanRelationService.getUserTrainingPlanRelationVO(userTrainingPlanRelation, request));
    }

    /**
     * 分页获取用户训练计划关系列表（仅管理员可用）
     *
     * @param userTrainingPlanRelationQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<UserTrainingPlanRelation>> listUserTrainingPlanRelationByPage(@RequestBody UserTrainingPlanRelationQueryRequest userTrainingPlanRelationQueryRequest) {
        long current = userTrainingPlanRelationQueryRequest.getCurrent();
        long size = userTrainingPlanRelationQueryRequest.getPageSize();
        // 查询数据库
        Page<UserTrainingPlanRelation> userTrainingPlanRelationPage = userTrainingPlanRelationService.page(new Page<>(current, size),
                userTrainingPlanRelationService.getQueryWrapper(userTrainingPlanRelationQueryRequest));
        return Result.success(userTrainingPlanRelationPage);
    }

    /**
     * 分页获取用户训练计划关系列表（封装类）
     *
     * @param userTrainingPlanRelationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserTrainingPlanRelationVO>> listUserTrainingPlanRelationVOByPage(@RequestBody UserTrainingPlanRelationQueryRequest userTrainingPlanRelationQueryRequest,
                                                               HttpServletRequest request) {
        long current = userTrainingPlanRelationQueryRequest.getCurrent();
        long size = userTrainingPlanRelationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserTrainingPlanRelation> userTrainingPlanRelationPage = userTrainingPlanRelationService.page(new Page<>(current, size),
                userTrainingPlanRelationService.getQueryWrapper(userTrainingPlanRelationQueryRequest));
        // 获取封装类
        return Result.success(userTrainingPlanRelationService.getUserTrainingPlanRelationVOPage(userTrainingPlanRelationPage, request));
    }

    /**
     * 分页获取当前登录用户创建的用户训练计划关系列表
     *
     * @param userTrainingPlanRelationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserTrainingPlanRelationVO>> listMyUserTrainingPlanRelationVOByPage(@RequestBody UserTrainingPlanRelationQueryRequest userTrainingPlanRelationQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(userTrainingPlanRelationQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        userTrainingPlanRelationQueryRequest.setUserId(loginUser.getId());
        long current = userTrainingPlanRelationQueryRequest.getCurrent();
        long size = userTrainingPlanRelationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserTrainingPlanRelation> userTrainingPlanRelationPage = userTrainingPlanRelationService.page(new Page<>(current, size),
                userTrainingPlanRelationService.getQueryWrapper(userTrainingPlanRelationQueryRequest));
        // 获取封装类
        return Result.success(userTrainingPlanRelationService.getUserTrainingPlanRelationVOPage(userTrainingPlanRelationPage, request));
    }

    /**
     * 编辑用户训练计划关系（给用户使用）
     *
     * @param userTrainingPlanRelationEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editUserTrainingPlanRelation(@RequestBody UserTrainingPlanRelationEditRequest userTrainingPlanRelationEditRequest, HttpServletRequest request) {
        if (userTrainingPlanRelationEditRequest == null || userTrainingPlanRelationEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        UserTrainingPlanRelation userTrainingPlanRelation = new UserTrainingPlanRelation();
        BeanUtils.copyProperties(userTrainingPlanRelationEditRequest, userTrainingPlanRelation);
        // 数据校验
        userTrainingPlanRelationService.validUserTrainingPlanRelation(userTrainingPlanRelation, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = userTrainingPlanRelationEditRequest.getId();
        UserTrainingPlanRelation oldUserTrainingPlanRelation = userTrainingPlanRelationService.getById(id);
        ThrowUtils.throwIf(oldUserTrainingPlanRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldUserTrainingPlanRelation.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userTrainingPlanRelationService.updateById(userTrainingPlanRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
    * 日新增统计用户训练计划关系
    *
    * @return
    */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedUserTrainingPlanRelation() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> userTrainingPlanRelationDataList = userTrainingPlanRelationService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(userTrainingPlanRelationDataList);

    }

    // endregion
}
